package org.theSeed.fileConfig.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.theSeed.base.exp.ServiceExp;
import org.theSeed.base.pojo.constant.SysConstant;
import org.theSeed.fileConfig.pojo.prop.SeedFileUploadProp;
import org.theSeed.fileContract.contract.FileContract;
import org.theSeed.fileContract.contract.UploadFileRecorder;
import org.theSeed.fileContract.exp.FileUploadExp;
import org.theSeed.fileContract.paramEncoder.SeedFileParamEncoder;
import org.theSeed.fileContract.paramEncoder.impl.ParamEncoderBase64;
import org.theSeed.fileContract.pojo.prop.FileConfigProp;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件配置集成
 */
@Configuration
public class SeedFileConfig {
    @Autowired
    public SeedFileUploadProp seedFileUploadProp;

    /**
     * 文件加密
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public SeedFileParamEncoder seedFileParamEncoder(){
        return new ParamEncoderBase64();
    }

    @Bean
    public SeedFileHolder seedFileHolder(@Autowired SeedFileParamEncoder seedFileParamEncoder,@Autowired UploadFileRecorder uploadFileRecorder){
        Map<String, FileContract> fileContractMap = new HashMap<>();
        Map<String, FileConfigProp> fileConfigPropMap = new HashMap<>();
        Map<String, Map<String, Object>> fileConfigMap = seedFileUploadProp.getFileConfigMap();
        if (ObjectUtil.isNull(fileConfigMap))
            throw new FileUploadExp("文件上传配置不能为空");
        fileConfigMap.entrySet().stream().forEach(entry->{
            String key = entry.getKey();
            Map<String, Object> value = entry.getValue();
            String clazzName = value.get("fileContractClazzName").toString();
            Class<?> clazz = null;
            try {
                clazz = Class.forName(clazzName);
            } catch (ClassNotFoundException e) {
                throw new FileUploadExp("文件上传实例为"+key+"的fileContractClazzName类不存在");
            }
            FileConfigProp fileConfigProp = (FileConfigProp) BeanUtil.mapToBean(value, clazz, true, SysConstant.copyOptions);
            fileConfigProp.checkParam();
            FileContract fileContract = fileConfigProp.createFileContract(key, seedFileUploadProp.getChipFileSize());
            fileConfigPropMap.put(key,fileConfigProp);
            fileContractMap.put(key,fileContract);
        });

        return new SeedFileHolder(seedFileUploadProp,fileConfigPropMap,fileContractMap,seedFileParamEncoder,uploadFileRecorder);
    }
}
